using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.ComponentModel;
using Sucrose.Base;

namespace Sucrose
{
    public class SucroseWorker : BackgroundWorker
    {
        private String currentMessage;

        /// <summary>
        /// Creates a new Worker, and adds listeners
        /// </summary>
        public SucroseWorker()
        {
            SucroseControl sc = SucroseControl.GetInstance();
            sc.ProgressUpdates += new ProgressUpdateHandler(ProgressUpdate);
            Logger.LogMessages += new LogMessageHandler(LogUpdate);

            WorkerReportsProgress = true;
        }

        /// <summary>
        /// Runs the 'DoAll' method asynchronously
        /// </summary>
        /// <param name="e"></param>
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            SucroseControl sc = SucroseControl.GetInstance();

            sc.DoAll();
        }

        /// <summary>
        /// Handles updates to the progress and transmits them via the background worker
        /// </summary>
        /// <param name="currentTicks">Completed ticks</param>
        /// <param name="totalTicks">Total ticks</param>
        private void ProgressUpdate(int currentTicks, int totalTicks)
        {
            if (currentTicks == 0)
            {
                this.currentMessage = "Done.";
                ReportProgress(0, this.currentMessage);
            }
            else
            {
                int progress = (int)(100 * ((float)currentTicks / (float)totalTicks));
                ReportProgress(Math.Min(progress, 100), this.currentMessage);
            }
        }

        /// <summary>
        /// Handles logging messages and transmits them via the background worker
        /// </summary>
        /// <param name="message">Message to display</param>
        /// <param name="type">Type of message that was sent</param>
        private void LogUpdate(string message, MessageType type)
        {
            this.currentMessage = message;
        }
    }
}
